package com.cdtu.service;

import com.cdtu.mapper.DeptMapper;
import com.cdtu.mapper.EmpMapper;
import com.cdtu.pojo.Dept;
import com.cdtu.pojo.DeptLog;
import com.cdtu.pojo.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService{

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;


    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//spring事务管理  默认回滚运行时异常
    public void delete(Integer id) throws Exception {
        try {
            deptMapper.delete(id);
//        id=1/0;       算数异常----->运行时异常
//            if (true){
//                throw new Exception("出错啦。。。");
//            }
            empMapper.deleteByDeptId(id);//根据ID删除该部门下所以员工
        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门操作，此次解散的是" + id + "号部门");
            deptLogService.insert(deptLog);
        }

    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.insert(dept);
    }

    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
